package com.qys.livesMall.finance.service.impl;

import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.IdGen;
import com.qys.livesMall.common.utils.SpringUtils;
import com.qys.livesMall.finance.model.dto.AccountHandle;
import com.qys.livesMall.finance.model.dto.AccountInfo;
import com.qys.livesMall.finance.model.dto.TransferAccountHandle;
import com.qys.livesMall.finance.service.AccountService;
import com.qys.livesMall.finance.service.TransferAccountsService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @menu TransferAccountsServiceImpl
 * @date 2023/07/28 18:02
 */
@Service
public class TransferAccountsServiceImpl implements TransferAccountsService {

    @Resource
    private ApplicationContext applicationContext;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TransferAccountHandle transfer(TransferAccountHandle handle) {
        //生成流水号
        IdGen idGen = IdGen.get();
        long serialNumber=idGen.nextId();
        //出帐
        AccountInfo out=handle.getOut();
        AccountHandle outHandle=new AccountHandle();
        BeanUtils.copyProperties(handle,outHandle);
        outHandle.setUserId(out.getUserId());
        outHandle.setShopId(out.getShopId());
        outHandle.setAccountType(out.getAccountType().getType());
        outHandle.setSerialNumber(serialNumber);
        AccountService outService=SpringUtils.getBean(out.getAccountType().getService());
        outHandle=outService.directOut(outHandle);
        if (!outHandle.getSuccess()){
            handle.setSuccess(false);
            handle.setMessage(outHandle.getMessage());
            return handle;
        }
        //入账
        AccountInfo in=handle.getIn();
        AccountHandle inHandle=new AccountHandle();
        BeanUtils.copyProperties(handle,inHandle);
        inHandle.setUserId(in.getUserId());
        inHandle.setShopId(in.getShopId());
        inHandle.setAccountType(in.getAccountType().getType());
        inHandle.setSerialNumber(serialNumber);
        AccountService inService=SpringUtils.getBean(in.getAccountType().getService());
        inHandle=inService.directIn(inHandle);
        if (!inHandle.getSuccess()){
            throw new QysException(inHandle.getMessage());
            //回滚
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

//            handle.setSuccess(false);
//            handle.setMessage(inHandle.getMessage());
//            return handle;
        }
        handle.setSuccess(true);
        handle.setSerialNumber(serialNumber);
        return handle;
    }

}

